package dem1;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-05-09
 * Time: 20:25
 */

public class BinarySearchTree {

    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    /**
     * 插入一个元素
     * @param key
     */
    public boolean insert(int key) {
        TreeNode cur = root;
        TreeNode curParent = root;
        TreeNode node = new TreeNode(key);
        if (root == null){
            root = node;
            return true;
        }
        while (cur != null){
            curParent = cur;
            if (cur.key > key){
                cur = cur.left;
            }else if (cur.key < key){
                cur = cur.right;
            }else {
                return false;
            }
        }
        if (curParent.key > key){
            curParent.left = node;
        }else {
            curParent.right = node;
        }
        return true;
    }
    //查找key是否存在
    public TreeNode search(int key) {
        TreeNode cur = root;
        while (cur != null){
            if (cur.key > key){
                cur = cur.left;
            }else if (cur.key < key){
                cur = cur.right;
            }else {
                return cur;
            }
        }
        return null;
    }
    //删除key的值
    public boolean remove(int key) {
        TreeNode curParant = root;
        TreeNode cur = root;
        while (cur == null  || cur.key != key){
            curParant = cur;
            if (cur.key > key){
                cur = cur.left;
            }else if (cur.key < key){
                cur = cur.right;
            }else {
                return removenode(cur,curParant);
            }
        }
        return false;
    }

    private boolean removenode(TreeNode cur, TreeNode curParant) {
        if (cur.left == null){
            if (cur == root){
                root = cur.right;
            }else if (curParant.right == cur){
                curParant.right = cur.right;
            }else {
                curParant.left = cur.right;
            }
        }else if (cur.right == null){
            if (cur == root){
                root = cur.left;
            }else if (curParant.right == cur){
                curParant.right = cur.left;
            }else {
                curParant.left = cur.left;
            }
        }else {
            TreeNode removenode = cur;
            curParant = cur;
            cur = cur.right;
            while (cur.left != null){
                curParant = cur;
                cur = cur.left;
            }
            removenode.key = cur.key;
            if (curParant.right == cur){
                curParant.right = cur.right;
            }else {
                curParant.left = cur.right;
            }
        }
        return true;
    }
}
